package com.javaweb.secondhand_trading.service.Impl;

import com.javaweb.secondhand_trading.Dto.OrderDto;
import com.javaweb.secondhand_trading.common.exception.BusinessException;
import com.javaweb.secondhand_trading.entity.Order;
import com.javaweb.secondhand_trading.entity.Product;
import com.javaweb.secondhand_trading.mapper.OrderMapper;
import com.javaweb.secondhand_trading.mapper.ProductMapper;
import com.javaweb.secondhand_trading.mapper.UserMapper;
import com.javaweb.secondhand_trading.service.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    private final OrderMapper orderMapper;
    private final ProductMapper productMapper;
    private final UserMapper userMapper;

    public OrderServiceImpl(OrderMapper orderMapper, ProductMapper productMapper, UserMapper userMapper){
        this.orderMapper = orderMapper;
        this.productMapper = productMapper;
        this.userMapper = userMapper;
    }

    @Override
    @Transactional
    public int createOrder(Order order) {
        Product product = productMapper.findById(order.getProductId());
        if(product == null){
            throw  new BusinessException("商品不存在");
        }

        if(!product.getUserId().equals(order.getSellerId())){
            throw new BusinessException("卖家信息不匹配");
        }

        // 设置初始状态和创建时间
        order.setStatus("pending");
        order.setCreatedAt(LocalDateTime.now());

        return orderMapper.insert(order);
    }

    @Override
    @Transactional
    public int updateOrderStatus(Integer orderId, String status) {
        // 获取当前订单状态
        Order order = orderMapper.selectById(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 更新状态
        return orderMapper.updateStatus(orderId, status);
    }

    @Override
    public int deleteOrder(Integer orderId) {
        return orderMapper.deleteOrders(orderId);
    }

    @Override
    public OrderDto getOrderDetail(Integer orderId) {
        return orderMapper.selectById(orderId);
    }

    @Override
    public List<Order> getBuyerOrders(Integer buyerId) {
        return orderMapper.selectByBuyerId(buyerId);
    }

    @Override
    public List<Order> getSellerOrders(Integer sellerId) {
        return orderMapper.selectBySellerId(sellerId);
    }
}
